#include "shader.h"

#include "Common/fileoperations.h"

#include <iostream>
#include <assert.h>

using namespace std;

namespace GL
{


Shader::Shader(const std::string& shader, bool isFilename)
: m_ProgramObject(0)
, m_ShaderId(0)
, m_ShaderContents(shader)
{
    if(isFilename)
    {
        if (!FileOperations::readTextFile(m_ShaderContents, shader))
        {
            cerr << "Failed to load shader: " << shader << endl;
        }
    }
    m_ProgramObject = glCreateProgram();
}


Shader::~Shader()
{
    glDeleteShader(m_ShaderId);
    glDeleteProgram(m_ProgramObject);
}


GLuint Shader::getShaderId()
{
    return m_ShaderId;
}

GLuint Shader::getProgramId()
{
    return m_ProgramObject;
}

void Shader::addUniformVariable(const std::string& name)
{
    GLint parameterIndex = glGetUniformLocation(m_ProgramObject, name.c_str());
    m_UniformVariables[name] = parameterIndex;
    assert(!glGetError());
}

void Shader::setUniformVariable(const std::string& name, int value)
{
    glUseProgram(m_ProgramObject);
    glUniform1i(m_UniformVariables[name], value);
    glUseProgram(GL_NONE);
    assert(!glGetError());
}

void Shader::setUniformVariable(const std::string& name, float value)
{
    glUseProgram(m_ProgramObject);
    glUniform1f(m_UniformVariables[name], value);
    glUseProgram(GL_NONE);
    assert(!glGetError());
}

bool Shader::link()
{
    glLinkProgram(m_ProgramObject);

    GLint success;
    glGetProgramiv(m_ProgramObject, GL_LINK_STATUS, &success);
    if (success == GL_FALSE)
    {
        cerr << "Program could not be linked" << endl;
        return false;
    }
    return true;
}

}
